package com.py.framework.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.py.framework.common.Constants;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.utils.DateUtils;
import com.py.framework.dao.UserDao;
import com.py.framework.entity.OfficeEntity;
import com.py.framework.entity.UserEntity;
import com.py.framework.service.OfficeService;
import com.py.framework.service.RoleService;
import com.py.framework.service.UserService;

/**
 * 用户管理Service实现
 * 
 * @author Leegern
 * @date 2018年4月25日
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleService roleService;
	@Autowired
	private OfficeService officeService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#queryUsersForPage(java.util.Map)
	 */
	@Override
	public List<UserEntity> queryUsersForPage(Map<String, Object> params) {
		return userDao.queryUsersForPage(params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#findOneUser(long)
	 */
	@Override
	public UserEntity findOneUser(long id) {
		if (id > Constants.NUMBER_ZERO) {
			return userDao.findOneUser(id);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#addUserInfo(com.py.framework.entity.
	 * UserEntity)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int addUserInfo(UserEntity entity) {
		entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
		entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		entity.setDelFlag(Constants.NUMBER_ONE);
		entity.setUserStatus(Constants.NUMBER_ONE);
		return userDao.addUserInfo(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#updateUserInfo(com.py.framework.
	 * entity.UserEntity)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int updateUserInfo(UserEntity entity) {
		entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		return userDao.updateUserInfo(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#batchDelUsers(java.util.List)
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int batchDelUsers(List<Long> ids, long currUserId) {
		int flag = 0;
		if (!CollectionUtils.isEmpty(ids)) {
			for (Long userId : ids) {
				if (currUserId == userId) {
					throw new ServiceException("无法删除当前用户，删除失败！");
				}
			}
			Map<String, Object> params = new HashMap<>();
			params.put("ids", ids);
			params.put("updateTime", new Timestamp(DateUtils.getCurrentDateTime().getTime()));
			flag = userDao.batchDelUsers(params);
			// 删除角色用户信息
			for (Long userId : ids) {
				params.clear();
				params.put("userId", userId);
				roleService.delRoleUserRelate(params);
			}
		}
		return flag;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#getUserByPrincipal(java.lang.String)
	 */
	@Override
	public UserEntity getUserByPrincipal(String username) {
		if (StringUtils.isNotBlank(username)) {
			return userDao.getUserByPrincipal(username);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#getUsersByAreaId(java.lang.String)
	 */
	@Override
	public List<UserEntity> getUsersByAreaId(String areaId) {
		if (StringUtils.isNotBlank(areaId)) {
			return userDao.getUsersByAreaId(areaId);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#getUsersByOfficeId(java.lang.String)
	 */
	@Override
	public List<UserEntity> getUsersByOfficeId(String officeId) {
		if (StringUtils.isNotBlank(officeId)) {
			return userDao.getUsersByOfficeId(officeId);
		}
		return null;
	}

	@Override
	public List<UserEntity> getDirectUsersByOfficeIds(String officeId) {
		if (StringUtils.isNotBlank(officeId)) {
			return userDao.getDirectUsersByOfficeId(officeId);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#getAllUsers()
	 */
	@Override
	public List<UserEntity> getAllUsers() {
		return userDao.getAllUsers();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#getUsersByName(java.lang.String)
	 */
	@Override
	public List<UserEntity> getUsersByName(String realName) {
		return userDao.getUsersByName(realName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.UserService#getUsersByUsername(java.lang.String)
	 */
	@Override
	public List<UserEntity> getUsersByUsername(String username) {
		if (StringUtils.isNotBlank(username)) {
			return userDao.getUsersByUsername(username);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#getUsersByIds(java.util.List)
	 */
	@Override
	public List<UserEntity> getUsersByIds(List<Long> ids) {
		if (!CollectionUtils.isEmpty(ids)) {
			return userDao.getUsersByIds(ids);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#getSubUsersById(long)
	 */
	@Override
	public List<UserEntity> getSubUsersById(long userId) {
		List<UserEntity> users = new ArrayList<>();
		if (userId > Constants.NUMBER_ZERO) {
			UserEntity user = this.findOneUser(userId);
			if (null != user && user.getOfficeId() > Constants.NUMBER_ZERO) {
				List<UserEntity> datas = userDao.getSubUsersById(userId);
				if (!CollectionUtils.isEmpty(datas)) {
					datas.addAll(datas);
				}
				users.add(user);
			}
		}
		return users;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.py.framework.service.UserService#getAreaAdminUsers(long, long)
	 */
	@Override
	public List<UserEntity> getAreaAdminUsers(long userId, long officeId) {
		Map<String, Object> params = new HashMap<>();
		if (userId > Constants.NUMBER_ZERO) {
			params.put("userId", userId);
		}
		if (officeId > Constants.NUMBER_ZERO) {
			OfficeEntity entity = officeService.findOneOffice(officeId);
			if (null != entity && entity.getAreaId() > Constants.NUMBER_ZERO) {
				params.put("areaId", entity.getAreaId());
			}
		}
		return userDao.getAreaAdminUsers(params);
	}

	/**
	 *
	 * @Function 判断是否存在重复部门管理员
	 * @FileName UserServiceImpl.java
	 * @MethodName getDeptAdminUsers
	 * @param userId
	 *            用户ID
	 * @param officeId
	 *            部门ID
	 * @return
	 * @Date 2018年7月26日 上午11:14:12
	 * @Author Min DongXv
	 *
	 */
	@Override
	public List<UserEntity> getDeptAdminUsers(long userId, long officeId) {
		Map<String, Object> params = new HashMap<>();
		if (userId > Constants.NUMBER_ZERO) {
			params.put("userId", userId);
		}
		params.put("officeId", officeId);
		return userDao.getDeptAdminUsers(params);
	}

	/**
	 *
	 * @Function 通过部门ID获取部门管理员信息
	 * @FileName UserServiceImpl.java
	 * @MethodName getAllDeptAdmin
	 * @param deptIds
	 *            部门ID
	 * @return
	 * @Date 2018年7月26日 上午11:27:44
	 * @Author Min DongXv
	 *
	 */
	@Override
	public List<UserEntity> getAllDeptAdmin(List<Long> deptIds) {
		return userDao.getAllDeptAdmin(deptIds);
	}

	@Override
	public int updateLog(UserEntity entity) {
		return userDao.updateLog(entity);
	}

	@Override
	public List<UserEntity> getDeptAllUsers(String deptId) {

		List<UserEntity> filter = new ArrayList<UserEntity>();

		List<UserEntity> deptAllUsers = userDao.getDeptAllUsers();

		if (StringUtils.isNotBlank(deptId)) {

			for (UserEntity userEntity : deptAllUsers) {

				String parentDeptId = userEntity.getParentDeptId();

				long officeId = userEntity.getOfficeId();

				String deptIdStr = String.valueOf(officeId);

				if (StringUtils.isNotBlank(parentDeptId) && !deptId.equals(deptIdStr)) {

					String[] split = parentDeptId.split(",");

					List<String> asList = Arrays.asList(split);

					if (asList.contains(deptId)) {

						filter.add(userEntity);

					}

				}

				if (deptId.equals(deptIdStr)) {

					filter.add(userEntity);

				}

			}
			return filter;
		} else {

			return deptAllUsers;
		}

	}

	@Override
	public List<Long> getDeptManager(List<Long> deptIds) {
		return userDao.getDeptManager(deptIds);
	}

	@Override
	public String getLhjcToken(long deptId) {
		return userDao.getLhjcToken(deptId);
	}

	@Override
	public UserEntity getUserByTwoPrincipal(String username) {
		if (StringUtils.isNotBlank(username)) {
			return userDao.getUserByTwoPrincipal(username);
		}
		return null;
	}

	@Override
	public List<LinkedHashMap> getManagerDeptList() {
		return userDao.getManagerDeptList();
	}

	/**
	 * 
	 *
	 * @Function 获取权限内的用户ID
	 * @FileName UserServiceImpl.java
	 * @MethodName getDealUser
	 * @param userInfo
	 * @return
	 * @Date 2018年12月3日 下午5:41:27
	 * @Author Min DongXv
	 *
	 */
	@Override
	public List<Long> getDealUser(UserEntity userInfo) {
		return userDao.getDealUser(userInfo.getOfficeId(), userInfo.getAreaId(), userInfo.getUserType());
	}
	@Override
	public List<String> findUserRole() {
		// TODO Auto-generated method stub
		return userDao.findUserRole();
	}
}